package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import com.itheima.transaction.TransactionManager;
import com.itheima.utils.DataSourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.RuntimeErrorException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 业务层意思
 *
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private TransactionManager transactionManager;


    @Override
    @SuppressWarnings("all")
    public void transfer(int from, int to, double money) {
        Connection connection=null;
        try {
            //开启事务
            /*connection= DataSourceUtil.getConnection(dataSource);
            connection.setAutoCommit(false);*/
            transactionManager.start();

            //业务逻辑start~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            accountDao.add(to,money);

            int i=5/0;

            accountDao.sub(from,money);


            //业务逻辑end~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



            //提交事务
            //connection.commit();
            transactionManager.commit();
        }catch (Exception e){
            //回滚
            /*try {
                //底层 向数据库发送一条指令 让数据库回滚数据
                connection.rollback();
            } catch (SQLException e1) {
                //do nothing~~~
            }*/

            transactionManager.rollback();

            throw new RuntimeException(e);

        }finally {
            //关闭资源
            /*try {
                //底层 向数据库发送一条指令 让数据库该链接可以关闭
                connection.close();
            } catch (SQLException e) {
                //do nothing~~~
            }*/
            DataSourceUtil.close();
        }








    }

    @Override
    public void delete(int id) {

        accountDao.delete(id);

    }

    @Override
    public void add(Account account) {

        accountDao.save(account);

    }

    @Override
    public Account findById(int id) {


        return accountDao.findById(id);
    }
}
